package com.example.paging.ui

import androidx.paging.PagingSource
import com.example.paging.entity.HomeVO
import com.example.paging.network.ArticleNetwork
import kotlinx.coroutines.delay

class HomePageSource: PagingSource<Int, HomeVO.Data.Datas>() {

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, HomeVO.Data.Datas> {
        // 如果key是null，那就加载第0页的数据
        val page = params.key ?: 0
        // 每一页的数据长度
        val pageSize = params.loadSize
        return try {
            delay(1000)
            val response = ArticleNetwork.getHomeArticles(page)
            LoadResult.Page(
                data = response.datas,
                prevKey = if (page == 0) null else page - 1,
                nextKey = if (response.over) null else page + 1
            )
        } catch (e: Exception) {
            LoadResult.Error(e)
        }
    }
}